﻿using MxWeiXinPF.BLL;
using Senparc.Weixin.MP.AdvancedAPIs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Senparc.Weixin.MP.AdvancedAPIs.User;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin;
using Senparc.Weixin.MP.Entities;

namespace MxWeiXinPF.WeiXinComm
{
    public class WeiXinCRMComm
    {
        private MxWeiXinPF.BLL.wx_property_info pBll = new MxWeiXinPF.BLL.wx_property_info();
        private MxWeiXinPF.BLL.wx_userweixin wBll = new MxWeiXinPF.BLL.wx_userweixin();

        private IList<string> baseUserOpenid(int wid, out string error)
        {
            IList<string> openidList = new List<string>();
            string accessTokenOrAppId = this.getAccessToken(wid, out error);
            if (error != "")
            {
                return null;
            }
            OpenIdResultJson json = UserApi.Get(accessTokenOrAppId, null);
            if (json.count == json.total)
            {
                openidList = json.data.openid;
            }
            else
            {
                this.getNextUserOpenid(wid, json.next_openid, openidList);
            }
            return openidList;
        }

        public string FlushAccessToken(int wid, out string error)
        {
            string str = "";
            error = "";
            try
            {
                MxWeiXinPF.Model.wx_userweixin model = this.wBll.GetModel(wid);
                if ((((model.AppId == null) || (model.AppSecret == null)) || (model.AppId.Trim().Length <= 0)) || (model.AppSecret.Trim().Length <= 0))
                {
                    error = "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息！";
                    return "";
                }
                str = CommonApi.GetToken(model.AppId, model.AppSecret, "client_credential").access_token;
                if (!this.pBll.ExistsWid(wid))
                {
                    this.pBll.AddAccess_Token(wid, str);
                }
                else
                {
                    MxWeiXinPF.Model.wx_property_info _info = new MxWeiXinPF.Model.wx_property_info();
                    _info = this.pBll.GetModelList("iName='access_token' and wid=" + wid)[0];
                    _info.iContent = str;
                    _info.createDate = new DateTime?(DateTime.Now);
                    this.pBll.Update(_info);
                }
            }
            catch (Exception exception)
            {
                error = "获得access_token出错:" + exception.Message;
            }
            return str;
        }

        public string getAccessToken(int wid, out string error)
        {
            string iContent = "";
            error = "";
            try
            {
                int? nullable2;
                MxWeiXinPF.Model.wx_userweixin model = this.wBll.GetModel(wid);
                if ((((model.AppId == null) || (model.AppSecret == null)) || (model.AppId.Trim().Length <= 0)) || (model.AppSecret.Trim().Length <= 0))
                {
                    error = "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息！";
                    return "";
                }

                AccessTokenResult tokenresult = CommonApi.GetToken(model.AppId, model.AppSecret);
                iContent = tokenresult.access_token;
                //MxWeiXinPF.Model.wx_property_info _info = new MxWeiXinPF.Model.wx_property_info();
                //if (!this.pBll.ExistsWid(wid))
                //{
                //    iContent = CommonApi.GetToken(model.AppId, model.AppSecret, "client_credential").access_token;
                //    this.pBll.AddAccess_Token(wid, iContent);
                //    return iContent;
                //}
                //_info = this.pBll.GetModelList("iName='access_token' and wid=" + wid)[0];
                //TimeSpan span = (TimeSpan)(DateTime.Now - _info.createDate.Value);
                //double totalSeconds = span.TotalSeconds;
                //if (((_info.iContent == null) || (_info.iContent.Trim() == "")) || ((totalSeconds >= ((double)(nullable2 = _info.expires_in).GetValueOrDefault())) && nullable2.HasValue))
                //{
                //    iContent = CommonApi.GetToken(model.AppId, model.AppSecret, "client_credential").access_token;
                //    _info.iContent = iContent;
                //    _info.createDate = new DateTime?(DateTime.Now);
                //    this.pBll.Update(_info);
                //}
                //else
                //{
                //    iContent = _info.iContent;
                //}
            }
            catch (Exception exception)
            {
                error = "获得access_token出错:" + exception.Message;
            }
            return iContent;
        }

        private void getNextUserOpenid(int wid, string nexOpenid, IList<string> openidList)
        {
            string error = "";
            OpenIdResultJson json = UserApi.Get(this.getAccessToken(wid, out error), nexOpenid);
            if ((json != null) && (json.count > 0))
            {
                for (int i = 0; i < json.data.openid.Count; i++)
                {
                    openidList.Add(json.data.openid[i]);
                }
                this.getNextUserOpenid(wid, json.next_openid, openidList);
            }
        }

        public UserInfoJson GetUserDetail(int wid, string openId)
        {
            string error = "";
            return UserApi.Info(this.getAccessToken(wid, out error), openId, Language.zh_CN);
        }
    }
}
